<template>
  <Modal v-model="visible"
         :title="dataForm.id ? '编辑用户' : '新增用户'"
         :closable="false"
         :mask-closable="false">
    <Form ref="dataForm" :model="dataForm" :rules="ruleValidate" :label-width="80">
      <FormItem label="用户名" prop="userName">
        <Input v-model="dataForm.userName" placeholder="输入用户名" clearable></Input>
      </FormItem>
      <FormItem label="密码" prop="password">
        <Input v-model="dataForm.password" :disabled="!disablePassword" type="password" placeholder="输入密码" :clearable="disablePassword"></Input>
      </FormItem>
      <FormItem label="密码确认" prop="confirmPassword">
        <Input v-model="dataForm.confirmPassword" :disabled="!disablePassword" type="password" placeholder="密码确认" :clearable="disablePassword"></Input>
      </FormItem>
      <FormItem label="邮箱" prop="email">
        <Input v-model="dataForm.email" placeholder="输入邮箱" clearable></Input>
      </FormItem>
      <FormItem label="手机号" prop="mobile">
        <Input v-model="dataForm.mobile" placeholder="输入手机号" clearable></Input>
      </FormItem>
      <FormItem label="账号状态">
        <i-switch size="large" v-model="dataForm.status" :true-value="1" :false-value="0">
          <span slot="open">正常</span>
          <span slot="close">禁用</span>
        </i-switch>
      </FormItem>
      <FormItem label="角色列表">
        <span v-if="roleList.length === 0">无角色信息</span>
        <Tag v-else
             ref="roleTag"
             v-for="(item, index) in roleList"
             :color="item.color"
             :key="item.roleId"
             :name="item.roleName"
             @click.native="handleCheck(item, index)"
             style="margin-left:10px;height: 28px;line-height: 28px;"
             :fade="false">{{ item.roleName }}
        </Tag>
      </FormItem>
      <!--<FormItem label="账号状态" prop="status">
        <RadioGroup v-model="dataForm.status">
          <Radio :label="1">正常</Radio>
          <Radio :label="0">禁用</Radio>
        </RadioGroup>
      </FormItem>-->
    </Form>
    <div slot="footer">
      <Button type="text" @click="handleCancel">取消</Button>
      <Button type="primary" :loading="showLoading" @click="handleSubmit">保存</Button>
    </div>
  </Modal>
</template>
<script>
export default {
  /* props: {
    visible: {
      type: Boolean,
      default: false
    }
  }, */
  data () {
    const validConfirmPassword = (rule, value, callback) => {
      if (this.dataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else {
        callback();
      }
    };
    return {
      visible: false,
      disablePassword: true,
      showLoading: false,
      roleList: [],
      dataForm: {
        id: 0,
        userName: '',
        password: '11111',
        confirmPassword: '11111',
        email: '',
        mobile: '',
        roleIdList: [],
        status: 1
      },
      ruleValidate: {
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: validConfirmPassword, trigger: 'blur' }
        ]
        /* ,
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '邮箱格式错误', trigger: 'blur' }
        ] */
      }
    }
  },
  methods: {
    init (id) {
      // add or update
      this.$refs['dataForm'].resetFields();
      // 清空角色id列表
      // this.dataForm.roleIdList.splice(0, this.dataForm.roleIdList.length);
      this.visible = true;
      this.dataForm.id = id || 0;
      this.$http({
        url: this.$http.adornUrl('/sys/role/select'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        const roles = data && data.code === 0 ? data.list : [];
        roles.forEach((item) => {
          item.color = 'default';
        });
        this.roleList = roles;
      }).then(() => {
        if (this.dataForm.id) {
          this.disablePassword = false;
          // 根据id获取详情
          this.$http({
            url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.userName = data.user.username;
              this.dataForm.email = data.user.email;
              this.dataForm.mobile = data.user.mobile;
              this.dataForm.status = data.user.status;
              this.dataForm.roleIdList = data.user.roleIdList;
            }
          }).then(() => {
            this.roleList.filter((item) => {
              this.dataForm.roleIdList.filter((id) => {
                if (item.roleId === id) {
                  item.color = '#cca4e3';
                }
              })
            });
          });
        }
      })
    },
    handleCheck (item, index) {
      if (this.$refs.roleTag[index].name === item.roleName) {
        if (this.roleList[index].color === '#cca4e3') {
          /* 选中状态，改为未选中，并且展示菜单详情 */
          this.roleList[index].color = 'default';
          // this.dataForm.roleIdList.pop();
        } else {
          /* 未选中状态，先选中 */
          this.roleList[index].color = '#cca4e3';
          // this.dataForm.roleIdList.push(item.roleId);
          /* this.roleList.forEach((role, i) => {
              if (i === index) {
                  this.dataForm.roleIdList.push(role.roleId);
              }
              role.color = i === index ? '#cca4e3' : 'default';
          }); */
        }
      }
    },
    handleCancel () {
      this.visible = false;
      this.disablePassword = true;
      this.showLoading = false;
    },
    updateSubmit () {
      this.$http({
        url: this.$http.adornUrl(`/sys/user/${this.dataForm.id ? 'update' : 'save'}`),
        method: 'post',
        data: this.$http.adornData({
          'userId': this.dataForm.id || undefined,
          'username': this.dataForm.userName,
          'email': this.dataForm.email,
          'mobile': this.dataForm.mobile,
          'status': this.dataForm.status,
          'roleIdList': this.dataForm.roleIdList
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$Message.success({
            content: '操作成功',
            duration: 2,
            onClose: () => {
              this.handleCancel();
              this.$emit('refreshDataList')
            }
          });
        } else {
          this.$Message.error(data.msg);
          this.showLoading = false;
        }
      })
    },
    handleSubmit () { // 表单提交
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.showLoading = true;
          // 清空roleIdList
          this.dataForm.roleIdList = [];
          // 获取角色id列表
          this.roleList.forEach((item) => {
            if (item.color === '#cca4e3' && this.dataForm.roleIdList.indexOf(item.roleId) === -1) {
              this.dataForm.roleIdList.push(item.roleId);
            }
          });
          if (this.dataForm.id) {
            this.updateSubmit();
          } else {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/${this.dataForm.id ? 'update' : 'save'}`),
              method: 'post',
              data: this.$http.adornData({
                'userId': this.dataForm.id || undefined,
                'username': this.dataForm.userName,
                'password': this.dataForm.password,
                'email': this.dataForm.email,
                'mobile': this.dataForm.mobile,
                'status': this.dataForm.status,
                'roleIdList': this.dataForm.roleIdList
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$Message.success({
                  content: '操作成功',
                  duration: 2,
                  onClose: () => {
                    this.handleCancel();
                    this.$emit('refreshDataList')
                  }
                });
              } else {
                this.$Message.error(data.msg);
                this.showLoading = false;
              }
            })
          }
        }
      })
    }
  }
}
</script>
